package com.zws.cucumber.bootstrap.cass;

import com.zws.cucumber.util.ZwsJavaHomeUtil;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.ReflectionUtils;

import javax.net.ServerSocketFactory;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class ZwsBootstrapUtil {

    public static final String jdk8Home = ZwsJavaHomeUtil.findJdk8Home();

    public static void makeFile(String filepath, String content) {
        try (PrintWriter pw = new PrintWriter(new FileWriter(filepath, false))) {
            pw.print(content);
            pw.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void extractFile(PathMatchingResourcePatternResolver resolver, String pattern, String targetPath) throws IOException {
        System.out.println("standalone-cassandra: " + pattern);
        Resource[] resources = resolver.getResources(pattern);
        Files.copy(
                resources[0].getInputStream(),
                new File(targetPath).toPath(),
                StandardCopyOption.REPLACE_EXISTING);
    }

    public static void setField(Object object, String name, Object value) {
        Class<?> clazz;
        Field field;
        if (object instanceof Class) {
            clazz = (Class<?>) object;
            object = null;
        } else {
            clazz = object.getClass();
        }

        field = ReflectionUtils.findField(clazz, name);
        field.setAccessible(true);
        ReflectionUtils.setField(field, object, value);
    }

    public static void println(Object msg) {
        System.out.println(msg);
    }

    public static void printf(String format, Object... args) {
        System.out.printf(format, args);
    }

    public static boolean isPortAvailable(int port) {
        try {
            ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(port, 1, InetAddress.getByName("localhost"));
            serverSocket.close();
            return true;
        } catch (Exception var3) {
            return false;
        }
    }

    private static long timestamp = 0L;

    public static long startTimer() {
        return timestamp = System.currentTimeMillis();
    }

    public static long elapsed() {
        long elapsed = System.currentTimeMillis() - timestamp;
        timestamp = System.currentTimeMillis();
        return elapsed;
    }
}
